import { useState } from 'react';
import { TaskResultsProps } from './types';

export const TaskResults = ({ taskQueue, taskResults, outputFiles, onDownload }: TaskResultsProps) => {
  const [activeTab, setActiveTab] = useState<'任务队列' | '任务结果'>('任务队列');
  const [expandedTaskId, setExpandedTaskId] = useState<string | null>(null);
  const [detailTab, setDetailTab] = useState<'细节' | '日志'>('细节');
  
  // 根据队列中任务的优先级显示不同的颜色
  const getPriorityColor = (priority: string) => {
    switch (priority) {
      case 'high': return 'text-red-500';
      case 'low': return 'text-gray-500';
      default: return 'text-blue-500';
    }
  };

  // 根据任务状态显示不同的颜色
  const getStatusColor = (status: string) => {
    switch (status) {
      case 'success': return 'text-green-500';
      case 'error': return 'text-red-500';
      case 'running': return 'text-blue-500';
      default: return 'text-gray-500';
    }
  };

  // 根据任务状态获取状态标签样式
  const getStatusBadgeStyle = (status: string) => {
    switch (status) {
      case 'success': return 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300';
      case 'error': return 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-300';
      case 'running': return 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300';
      default: return 'bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300';
    }
  };

  // 切换任务详情展开/折叠
  const toggleTaskDetails = (taskId: string) => {
    setExpandedTaskId(expandedTaskId === taskId ? null : taskId);
    setDetailTab('细节'); // 默认显示细节标签
  };

  // 转换状态为中文
  const getStatusText = (status: string) => {
    switch (status) {
      case 'success': return '成功';
      case 'error': return '错误';
      case 'running': return '执行中';
      case 'waiting': return '等待中';
      default: return status;
    }
  };

  // 模拟任务日志内容
  const getTaskLogs = (taskId: string) => {
    const task = taskResults.find(t => t.id === taskId);
    if (!task) return [];
    if (!task.logs || task.logs.length === 0) {
      return [{
        createdAt: new Date().toLocaleTimeString(),
        message: "无任务日志产生"
      }];
    }
    return task.logs;
  };

  return (
    <>
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow-md overflow-hidden">
        <div className="border-b dark:border-gray-700">
          <div className="flex">
            <button
              className={`px-4 py-3 flex-1 text-center ${
                activeTab === '任务队列'
                  ? 'text-blue-500 border-b-2 border-blue-500'
                  : 'text-gray-500 dark:text-gray-400'
              }`}
              onClick={() => setActiveTab('任务队列')}
            >
              任务队列
            </button>
            <button
              className={`px-4 py-3 flex-1 text-center ${
                activeTab === '任务结果'
                  ? 'text-blue-500 border-b-2 border-blue-500'
                  : 'text-gray-500 dark:text-gray-400'
              }`}
              onClick={() => setActiveTab('任务结果')}
            >
              任务结果
            </button>
          </div>
        </div>

        <div className="p-4">
          {activeTab === '任务队列' ? (
            <div className="space-y-3">
              {taskQueue.length === 0 ? (
                <div className="text-center text-gray-500 dark:text-gray-400 py-4">
                  队列中暂无任务
                </div>
              ) : (
                taskQueue.map(task => (
                  <div 
                    key={task.id} 
                    className="border dark:border-gray-700 rounded-md p-3"
                  >
                    <div className="flex justify-between items-center">
                      <div className="font-medium dark:text-white">{task.taskTitle}</div>
                      <div className={`text-xs px-2 py-1 rounded-full ${
                        task.status === 'running' 
                          ? 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300'
                          : task.status === 'success'
                          ? 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300'
                          : 'bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300'
                      }`}>
                        {task.status === 'running' 
                          ? '执行中' 
                          : task.status === 'success'
                          ? '成功'
                          : '等待中'}
                      </div>
                    </div>
                    <div className="mt-2 flex items-center text-xs">
                      <div className={`${getPriorityColor(task.priority)} font-medium`}>
                        {task.priority === 'high' ? '高优先级' : task.priority === 'low' ? '低优先级' : '普通优先级'}
                      </div>
                    </div>
                  </div>
                ))
              )}
            </div>
          ) : (
            <div className="space-y-4 max-h-[500px] overflow-y-auto">
              {taskResults.filter(task => task.status !== 'waiting').length === 0 ? (
                <div className="text-center text-gray-500 dark:text-gray-400 py-4">
                  暂无任务执行结果
                </div>
              ) : (
                taskResults
                  .filter(task => task.status !== 'waiting')
                  .sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
                  .map(task => (
                    <div 
                      key={task.id} 
                      className="border dark:border-gray-700 rounded-md overflow-hidden bg-white dark:bg-gray-800"
                    >
                      {expandedTaskId !== task.id ? (
                        <div 
                          className="p-3 cursor-pointer"
                          onClick={() => toggleTaskDetails(task.id)}
                        >
                          <div className="flex justify-between items-center">
                            <div className="font-medium dark:text-white flex items-center">
                              <span className={`mr-2 ${getStatusColor(task.status)}`}>
                                {task.status === 'success' ? '✓' : task.status === 'error' ? '✕' : '⟳'}
                              </span>
                              {task.taskTitle}
                            </div>
                            <div className={`text-xs px-2 py-1 rounded-full ${getStatusBadgeStyle(task.status)}`}>
                              {getStatusText(task.status)}
                            </div>
                          </div>
                          <div className="text-xs mt-1 text-gray-500 dark:text-gray-400">
                            {new Date(task.createdAt).toLocaleString()}
                            {task.duration && ` · 用时: ${task.duration}`}
                          </div>
                        </div>
                      ) : (
                        <div>
                          {/* 任务详情头部 */}
                          <div className="p-3 border-b dark:border-gray-700">
                            <div className="flex justify-between items-center">
                              <div className="flex items-center">
                                <span className={`mr-2 text-xl ${getStatusColor(task.status)}`}>
                                  {task.status === 'success' ? '✓' : task.status === 'error' ? '✕' : '⟳'}
                                </span>
                                <span className="font-medium text-lg dark:text-white">{task.taskTitle}</span>
                              </div>
                              <div className={`px-2 py-1 rounded-full text-sm ${getStatusBadgeStyle(task.status)}`}>
                                {getStatusText(task.status)}
                              </div>
                            </div>
                          </div>
                          
                          {/* 切换标签 */}
                          <div className="flex border-b dark:border-gray-700">
                            <button
                              className={`flex-1 py-2 px-4 text-center ${
                                detailTab === '细节'
                                  ? 'text-blue-500 border-b-2 border-blue-500'
                                  : 'text-gray-500 dark:text-gray-400'
                              }`}
                              onClick={() => setDetailTab('细节')}
                            >
                              细节
                            </button>
                            <button
                              className={`flex-1 py-2 px-4 text-center ${
                                detailTab === '日志'
                                  ? 'text-blue-500 border-b-2 border-blue-500'
                                  : 'text-gray-500 dark:text-gray-400'
                              }`}
                              onClick={() => setDetailTab('日志')}
                            >
                              日志
                            </button>
                          </div>
                          
                          {/* 内容部分 */}
                          {detailTab === '细节' ? (
                            <div className="p-4">
                              <p className="text-gray-700 dark:text-gray-300 mb-4">
                                {task.taskGuide}
                              </p>
                              
                              {task.error && (
                                <div className="mt-4 p-2 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-md text-red-600 dark:text-red-400">
                                  {task.error}
                                </div>
                              )}
                              
                              <div className="border dark:border-gray-700 rounded-md overflow-hidden mb-3 bg-gray-100 dark:bg-gray-900 flex items-center justify-center h-48">
                                {task.screenshot && (
                                  <div className="mt-4">
                                    <h4 className="text-sm font-medium mb-2 dark:text-white">截图</h4>
                                    <img 
                                      src={task.screenshot} 
                                      alt="结果截图" 
                                      className="max-w-full h-auto border border-gray-200 dark:border-gray-700 rounded-md"
                                    />
                                  </div>
                                )}
                              </div>
                              
                              <div className="text-xs text-gray-500 dark:text-gray-400 text-right">
                                {new Date(task.createdAt).toLocaleString()}
                              </div>
                            </div>
                          ) : (
                            <div className="p-4">
                              <div className="bg-gray-50 dark:bg-gray-900 border dark:border-gray-700 rounded-md p-4 font-mono text-sm">
                                {getTaskLogs(task.id).map((log, index) => (
                                  <div key={index} className="mb-2 text-gray-700 dark:text-gray-300">
                                    {log.createdAt} : {log.message}
                                  </div>
                                ))}
                              </div>
                            </div>
                          )}
                          
                          {/* 底部按钮 */}
                          <div className="p-3 border-t dark:border-gray-700 flex justify-end">
                            <button 
                              className="text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300 mr-4"
                              onClick={() => setExpandedTaskId(null)}
                            >
                              关闭
                            </button>
                            <button className="text-blue-500 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300">
                              重新运行
                            </button>
                          </div>
                        </div>
                      )}
                    </div>
                  ))
              )}
            </div>
          )}
        </div>
      </div>

      <div className="bg-white dark:bg-gray-800 rounded-lg shadow-md mt-4">
        <div className="p-4">
          <h2 className="text-lg font-medium mb-4 dark:text-white">输出文件</h2>
          
          <div className="space-y-3">
            {outputFiles.length === 0 ? (
              <div className="text-center text-gray-500 dark:text-gray-400 py-4">
                暂无输出文件
              </div>
            ) : (
              outputFiles.map((file) => (
                <div key={file.name} className="flex items-center justify-between p-3 border dark:border-gray-700 rounded-md">
                  <div className="flex items-center">
                    <div className="mr-3">
                      <div className="w-8 h-8 bg-blue-100 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400 flex items-center justify-center rounded">
                        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 21h10a2 2 0 002-2V9.414a1 1 0 00-.293-.707l-5.414-5.414A1 1 0 0012.586 3H7a2 2 0 00-2 2v14a2 2 0 002 2z" />
                        </svg>
                      </div>
                    </div>
                    <div>
                      <div className="font-medium dark:text-white">{file.name}</div>
                      <div className="text-xs text-gray-500 dark:text-gray-400">
                        {typeof file.size === 'number' 
                          ? `${(file.size / 1024).toFixed(2)} KB` 
                          : file.size}
                      </div>
                    </div>
                  </div>
                  <button 
                    onClick={() => {
                      const taskId = file.id.split(':')[0];
                      onDownload(taskId, file.name);
                    }}
                    className="text-blue-500 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300"
                  >
                    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
                    </svg>
                  </button>
                </div>
              ))
            )}
          </div>
        </div>
      </div>
    </>
  );
}; 

export default TaskResults;